name: docs-preview-pr

on:
  workflow_run:
    workflows: [docs-build]
    types: [completed]

env:
  WF_ID: ${{ github.event.workflow_run.id }}
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

jobs:
  # Always determine if GitHub Pages are configured for this repo.
  get-gh-pages-url:
    if:
      github.event.workflow_run.event == 'pull_request' &&
      github.event.workflow_run.conclusion == 'success'
    runs-on: ubuntu-latest
    outputs:
      url: ${{ steps.api-resp.outputs.html_url || '' }}
      branch: ${{ steps.api-resp.outputs.branch || '' }}
    steps:
      - name: Check for GitHub Pages
        id: api-resp
        run: |
            has_pages=$(gh api "repos/${GITHUB_REPOSITORY}" -q '.has_pages')
            if [ "true" != "${has_pages}" ]; then
              echo "GitHub pages is not active for the repository. Quitting."
              return
            fi

            url=$(gh api "repos/${GITHUB_REPOSITORY}/pages" -q '.html_url')
            branch=$(gh api "repos/${GITHUB_REPOSITORY}/pages" -q '.source.branch')

            echo "html_url=${url}" >> $GITHUB_OUTPUT
            echo "branch=${branch}" >> $GITHUB_OUTPUT

  # Identify the dir for the HTML.
  store-html:
    runs-on: ubuntu-latest
    needs: [get-gh-pages-url]
    if: needs.get-gh-pages-url.outputs.url != ''
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ needs.get-gh-pages-url.outputs.branch }}
      - name: Initialize Git configuration
        run: |
          git config user.name docs-preview
          git config user.email do-not-send-@github.com
      - name: Download artifacts
        run: |
          gh run view "${WF_ID}"
          gh run download "${WF_ID}"
          PR=$(cat ./pr/pr.txt)
          MERGED=$(cat ./pr/merged.txt)
          ACTION=$(cat ./pr/action.txt)
          echo "PR_NO=${PR}" >> $GITHUB_ENV
          echo "MERGE_STATUS=${MERGED}" >> $GITHUB_ENV
          echo "PR_ACTION=${ACTION}" >> $GITHUB_ENV
          echo "REVIEW_DIR=review/" >> $GITHUB_ENV
          echo "PR_REVIEW_DIR=review/pr-${PR}" >> $GITHUB_ENV

          # Remove the pr artifact directory so that it does not
          # appear in listings or confuse git with untracked files.
          rm -rf ./pr

      # Permutations:
      # - PR was updated, PR_ACTION is !closed, need to delete review directory and update it.
      # - PR was closed (regardless of merge), PR_ACTION is closed, need to delete review directory.

      # If this PR is still open, store HTML in a review directory.
      - name: Handle HTML review directory for open PRs and updates to PRs
        if: env.MERGE_STATUS == 'false' && env.PR_ACTION != 'closed'
        run: |
          rm -rf "${{ env.PR_REVIEW_DIR }}" 2>/dev/null || true
          if [ ! -d "${{ env.REVIEW_DIR }}" ]; then
            mkdir "${{ env.REVIEW_DIR }}"
          fi
          mv ./html-build-artifact/latest/ "${{ env.PR_REVIEW_DIR }}"
          git add "${{ env.PR_REVIEW_DIR }}"
      # If the PR was closed, merged or not, delete review directory.
      - name: Delete HTML review directory for closed PRs
        if: env.PR_ACTION == 'closed'
        run: |
          if [ -d ./html-build-artifact/ ]; then
            rm -rf ./html-build-artifact/ 2>/dev/null
          fi
          if [ -d "${{ env.PR_REVIEW_DIR }}" ]; then
            git rm -rf "${{ env.PR_REVIEW_DIR }}"
          fi
      - name: Commit changes to the GitHub Pages branch
        run: |
          git status
          if git commit -m 'Pushing changes to GitHub Pages.'; then
            git push -f
          else
           echo "Nothing changed."
          fi
      - name: Check for existing documentation review comment
        run: |
          result=$(gh pr view ${{ env.PR_NO }} --json comments -q 'any(.comments[].body; contains("Documentation preview"))')
          echo "COMMENT_EXISTS=${result}" >> $GITHUB_ENV
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
      - name: Add HTML review URL comment to a newly opened PR
        if: env.MERGE_STATUS == 'false' && env.COMMENT_EXISTS == 'false'
        env:
          URL: ${{ needs.get-gh-pages-url.outputs.url }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        shell: bash
        run: |
          echo -e "## Documentation preview"                  > body
          echo -e ""                                         >> body
          echo -e "<${{ env.URL }}${{ env.PR_REVIEW_DIR }}>" >> body
          cat body
          gh pr comment ${{ env.PR_NO }} --body-file body
